﻿#region

using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using InfoTech.Utilities.Image;
using InfoTech.VinhSon.Bussiness;
using InfoTech.VinhSon.Models;
using Telerik.Web.Mvc;

#endregion

namespace VinhSon.Areas.Administrator.Controllers
{
    public class CategoryController : BaseAdministratorController
    {
        #region Category

        public ActionResult Index()
        {
            return View();
        }

        [GridAction]
        public ActionResult GetList()
        {
            return View(new GridModel(UnitOfWork.CategoryRepository.Select(c => c.Inactive == false || c.Inactive == null)
                                                .Select(c => new
                                                                 {
                                                                         c.Id,
                                                                         c.Name,
                                                                         c.Activated,
                                                                         c.IsShowMenu,
                                                                         c.Priority,
                                                                         Parent = c.Parent.Name,
                                                                         c.Url,
                                                                         c.LastModified
                                                                 })));
        }

        public ActionResult Add()
        {
            List<SelectListItem> list = new List<SelectListItem>
                                            {
                                                    new SelectListItem
                                                        {
                                                                Text = "",
                                                                Value = "0"
                                                        }
                                            };
            list.AddRange(UnitOfWork.CategoryRepository.Select(c => c.Inactive == false || c.Inactive == null,
                                                               c => c.Name)
                                    .Select(c => new
                                                     {
                                                             c.Id,
                                                             c.Name
                                                     })
                                    .ToList()
                                    .Select(c => new SelectListItem
                                                     {
                                                             Text = c.Name,
                                                             Value = c.Id + ""
                                                     }));
            ViewBag.Categories = list;
            return View(new CategoryModel
                            {
                                    Activated = true
                            });
        }

        [ValidateInput(false)]
        [HttpPost]
        public ActionResult Add(CategoryModel categoryModel)
        {
            if(ModelState.IsValid)
            {
                Category category = categoryModel;
                if(UnitOfWork.CategoryRepository.CheckInsertCategory(category))
                {
                    category.Parent = UnitOfWork.CategoryRepository.SelectbyId(categoryModel.ParentId ?? 0);
                    category.Url = ConvertToUnSign(category.Name);
                    UnitOfWork.CategoryRepository.Insert(category);
                    UnitOfWork.Save();

                    return RedirectToAction("Index");
                }
            }
            List<SelectListItem> list = new List<SelectListItem>
                                            {
                                                    new SelectListItem
                                                        {
                                                                Text = "",
                                                                Value = "0"
                                                        }
                                            };
            list.AddRange(UnitOfWork.CategoryRepository.Select(c => c.Inactive == false || c.Inactive == null,
                                                               c => c.Name)
                                    .Select(c => new
                                                     {
                                                             c.Id,
                                                             c.Name
                                                     })
                                    .ToList()
                                    .Select(c => new SelectListItem
                                                     {
                                                             Text = c.Name,
                                                             Value = c.Id + ""
                                                     }));
            ViewBag.Categories = list;
            return View(categoryModel);
        }

        public ActionResult Edit(string id)
        {
            int guid;
            if(int.TryParse(id,
                            out guid))
            {
                Category category = UnitOfWork.CategoryRepository.SelectbyId(guid);
                if(category != null)
                {
                    List<SelectListItem> list = new List<SelectListItem>
                                                    {
                                                            new SelectListItem
                                                                {
                                                                        Text = "",
                                                                        Value = "0"
                                                                }
                                                    };
                    list.AddRange(UnitOfWork.CategoryRepository.Select(c => c.Inactive == false || c.Inactive == null,
                                                                       c => c.Name)
                                            .Select(c => new
                                                             {
                                                                     c.Id,
                                                                     c.Name
                                                             })
                                            .ToList()
                                            .Select(c => new SelectListItem
                                                             {
                                                                     Text = c.Name,
                                                                     Value = c.Id + ""
                                                             }));
                    ViewBag.Categories = list;

                    CategoryModel categoryModel = category;
                    return View(categoryModel);
                }
            }
            return RedirectToAction("Index");
        }

        [ValidateInput(false)]
        [HttpPost]
        public ActionResult Edit(CategoryModel categoryModel)
        {
            if(ModelState.IsValid)
            {
                Category category = UnitOfWork.CategoryRepository.SelectbyId(categoryModel.Id);
                categoryModel.Update(category);
                if(UnitOfWork.CategoryRepository.CheckUpdateCategory(category))
                {
                    category.Parent = UnitOfWork.CategoryRepository.SelectbyId(categoryModel.ParentId ?? 0);
                    category.Url = ConvertToUnSign(category.Name);
                    UnitOfWork.CategoryRepository.Update(category);
                    UnitOfWork.Save();
                    return RedirectToAction("Index");
                }
            }
            List<SelectListItem> list = new List<SelectListItem>
                                            {
                                                    new SelectListItem
                                                        {
                                                                Text = "",
                                                                Value = "0"
                                                        }
                                            };
            list.AddRange(UnitOfWork.CategoryRepository.Select(c => c.Inactive == false || c.Inactive == null,
                                                               c => c.Name)
                                    .Select(c => new
                                                     {
                                                             c.Id,
                                                             c.Name
                                                     })
                                    .ToList()
                                    .Select(c => new SelectListItem
                                                     {
                                                             Text = c.Name,
                                                             Value = c.Id + ""
                                                     }));
            ViewBag.Categories = list;
            return View(categoryModel);
        }

        [HttpPost]
        public ActionResult Delete(string id)
        {
            if(id != null)
            {
                string[] s = id.Split(',');
                int guid;
                List<int> list = (from s1 in s
                                  where int.TryParse(s1,
                                                     out guid)
                                  select int.Parse(s1)).ToList();

                if(UnitOfWork.CategoryRepository.CheckDeleteCategory(list))
                {
                    UnitOfWork.CategoryRepository.Delete(list);
                    UnitOfWork.Save();
                }
            }
            return Json(new
                            {
                                    status = 1,
                                    msg = "Update Successfully"
                            },
                        JsonRequestBehavior.DenyGet);
        }

        #endregion

        #region Option

        public ActionResult Option(CategoryModel model)
        {
            return PartialView(model);
        }

        [HttpPost]
        public ActionResult UpdateOption(int id,
                                         int key,
                                         bool status)
        {
            Category category = UnitOfWork.CategoryRepository.SelectbyId(id);
            if(category != null)
            {
                if(!category.Status.HasValue)
                    category.Status = 0;
                if(status)
                    category.Status = category.Status.Value | key;
                else
                    category.Status = category.Status.Value & ~key;
                UnitOfWork.Save();
            }
            return Json(new
                            {
                                    status = 1,
                                    msg = "Update Successfully"
                            },
                        JsonRequestBehavior.DenyGet);
        }

        #endregion

        #region CSection

        public ActionResult Section(int id)
        {
            ViewBag.Id = id;
            return PartialView();
        }

        [GridAction]
        public ActionResult GetSectionList(int id)
        {
            return View(new GridModel(UnitOfWork.CSectionRepository.Select(c => c.Category.Id == id && (c.Inactive == false || c.Inactive == null))
                                                .Select(c => new
                                                                 {
                                                                         c.Id,
                                                                         c.Name,
                                                                         c.Priority,
                                                                         c.Type,
                                                                         c.Activated
                                                                 })));
        }

        public ActionResult AddSection(int id)
        {
            return View(new CSectionModel
                            {
                                    CategoryId = id,
                                    Activated = true
                            });
        }

        [ValidateInput(false)]
        [HttpPost]
        public ActionResult AddSection(CSectionModel sectionModel)
        {
            if(ModelState.IsValid)
            {
                CSection section = sectionModel;
                if(UnitOfWork.CSectionRepository.CheckInsertCSection(section))
                {
                    if(sectionModel.CategoryId.HasValue)
                        section.Category = UnitOfWork.CategoryRepository.SelectbyId(sectionModel.CategoryId.Value);
                    section.Type = CSection.SECTION;
                    UnitOfWork.CSectionRepository.Insert(section);
                    UnitOfWork.Save();

                    ViewBag.Completed = true;
                }
            }
            return View(sectionModel);
        }

        public ActionResult EditSection(string id)
        {
            int guid;
            if(int.TryParse(id,
                            out guid))
            {
                CSection section = UnitOfWork.CSectionRepository.SelectbyId(guid);
                if(section != null)
                {
                    CSectionModel sectionModel = section;
                    return View(sectionModel);
                }
            }
            ViewBag.Completed = true;
            return View(new CSectionModel());
        }

        [ValidateInput(false)]
        [HttpPost]
        public ActionResult EditSection(CSectionModel sectionModel)
        {
            if(ModelState.IsValid)
            {
                CSection section = UnitOfWork.CSectionRepository.SelectbyId(sectionModel.Id);
                sectionModel.Update(section);
                if(UnitOfWork.CSectionRepository.CheckUpdateCSection(section))
                {
                    UnitOfWork.CSectionRepository.Update(section);
                    UnitOfWork.Save();

                    ViewBag.Completed = true;
                }
            }
            return View(sectionModel);
        }

        public ActionResult AddDocument(int id)
        {
            return View(new CSectionModel
                            {
                                    CategoryId = id,
                                    Activated = true
                            });
        }

        [ValidateInput(false)]
        [HttpPost]
        public ActionResult AddDocument(CSectionModel sectionModel)
        {
            if(Request.Files.Count == 0)
                ModelState.AddModelError("Url",
                                         "Upload file is required");
            if(ModelState.IsValid)
            {
                CSection section = sectionModel;
                if(UnitOfWork.CSectionRepository.CheckInsertCSection(section))
                {
                    if(sectionModel.CategoryId.HasValue)
                        section.Category = UnitOfWork.CategoryRepository.SelectbyId(sectionModel.CategoryId.Value);

                    section.Type = CSection.DOCUMENT;
                    UnitOfWork.CSectionRepository.Insert(section);
                    UnitOfWork.Save();

                    // save document
                    HttpPostedFileBase file = Request.Files[0];
                    if(file != null)
                        if(file.ContentLength > 0)
                        {
                            section.Url = string.Format("{0}_{1}_{2}",
                                                        section.Id,
                                                        ConvertToUnSign(section.Name),
                                                        file.FileName);
                            file.SaveAs(string.Format("{0}{1}",
                                                      Server.MapPath("~/Resource/Document/"),
                                                      section.Url));
                            UnitOfWork.Save();
                        }

                    ViewBag.Completed = true;
                }
            }
            return View(sectionModel);
        }

        public ActionResult EditDocument(string id)
        {
            int guid;
            if(int.TryParse(id,
                            out guid))
            {
                CSection section = UnitOfWork.CSectionRepository.SelectbyId(guid);
                if(section != null)
                {
                    CSectionModel sectionModel = section;
                    return View(sectionModel);
                }
            }
            ViewBag.Completed = true;
            return View(new CSectionModel());
        }

        [ValidateInput(false)]
        [HttpPost]
        public ActionResult EditDocument(CSectionModel sectionModel)
        {
            if(ModelState.IsValid)
            {
                CSection section = UnitOfWork.CSectionRepository.SelectbyId(sectionModel.Id);

                string fileName = section.Url;

                sectionModel.Update(section);
                if(UnitOfWork.CSectionRepository.CheckUpdateCSection(section))
                {
                    // save document
                    HttpPostedFileBase file = Request.Files[0];
                    if(file != null)
                        if(file.ContentLength > 0)
                        {
                            // delete old resource
                            if(System.IO.File.Exists(string.Format("{0}{1}",
                                                                   Server.MapPath("~/Resource/Document/"),
                                                                   fileName)))
                                System.IO.File.Delete(string.Format("{0}{1}",
                                                                    Server.MapPath("~/Resource/Document/"),
                                                                    fileName));

                            section.Url = string.Format("{0}_{1}_{2}",
                                                        section.Id,
                                                        ConvertToUnSign(section.Name),
                                                        file.FileName);
                            file.SaveAs(string.Format("{0}{1}",
                                                      Server.MapPath("~/Resource/Document/"),
                                                      section.Url));
                        }
                        else
                            section.Url = fileName;
                    else
                        section.Url = fileName;

                    UnitOfWork.CSectionRepository.Update(section);
                    UnitOfWork.Save();

                    ViewBag.Completed = true;
                }
            }
            return View(sectionModel);
        }

        public ActionResult AddImage(int id)
        {
            return View(new CSectionModel
                            {
                                    CategoryId = id,
                                    Activated = true
                            });
        }

        [ValidateInput(false)]
        [HttpPost]
        public ActionResult AddImage(CSectionModel sectionModel)
        {
            if(Request.Files.Count == 0)
                ModelState.AddModelError("Url",
                                         "Upload file is required");
            if(ModelState.IsValid)
            {
                CSection section = sectionModel;
                if(UnitOfWork.CSectionRepository.CheckInsertCSection(section))
                {
                    if(sectionModel.CategoryId.HasValue)
                        section.Category = UnitOfWork.CategoryRepository.SelectbyId(sectionModel.CategoryId.Value);

                    section.Type = CSection.IMAGE;
                    UnitOfWork.CSectionRepository.Insert(section);
                    UnitOfWork.Save();

                    // save document
                    HttpPostedFileBase file = Request.Files[0];
                    if(file != null)
                        if(file.ContentLength > 0)
                        {
                            section.Url = string.Format("{0}_{1}_{2}",
                                                        section.Id,
                                                        ConvertToUnSign(section.Name),
                                                        file.FileName);
                            ProcessScaleImage.CreateThumbnail(file.InputStream,
                                                              90,
                                                              60)
                                             .Save(string.Format("{0}{1}",
                                                                 Server.MapPath("~/Resource/Images/thumb_"),
                                                                 section.Url));

                            ProcessScaleImage.CreateThumbnail(file.InputStream,
                                                              section.Width ?? 0,
                                                              section.Height ?? 0)
                                             .Save(string.Format("{0}{1}",
                                                                 Server.MapPath("~/Resource/Images/"),
                                                                 section.Url));
                            UnitOfWork.Save();
                        }

                    ViewBag.Completed = true;
                }
            }
            return View(sectionModel);
        }

        public ActionResult EditImage(string id)
        {
            int guid;
            if(int.TryParse(id,
                            out guid))
            {
                CSection section = UnitOfWork.CSectionRepository.SelectbyId(guid);
                if(section != null)
                {
                    CSectionModel sectionModel = section;
                    return View(sectionModel);
                }
            }
            ViewBag.Completed = true;
            return View(new CSectionModel());
        }

        [ValidateInput(false)]
        [HttpPost]
        public ActionResult EditImage(CSectionModel sectionModel)
        {
            if(ModelState.IsValid)
            {
                CSection section = UnitOfWork.CSectionRepository.SelectbyId(sectionModel.Id);

                string fileName = section.Url;

                sectionModel.Update(section);
                if(UnitOfWork.CSectionRepository.CheckUpdateCSection(section))
                {
                    // save document
                    HttpPostedFileBase file = Request.Files[0];
                    if(file != null)
                        if(file.ContentLength > 0)
                        {
                            // delete old resource
                            if(System.IO.File.Exists(string.Format("{0}{1}",
                                                                   Server.MapPath("~/Resource/Images/"),
                                                                   fileName)))
                                System.IO.File.Delete(string.Format("{0}{1}",
                                                                    Server.MapPath("~/Resource/Images/"),
                                                                    fileName));
                            if(System.IO.File.Exists(string.Format("{0}{1}",
                                                                   Server.MapPath("~/Resource/Images/thumb_"),
                                                                   fileName)))
                                System.IO.File.Delete(string.Format("{0}{1}",
                                                                    Server.MapPath("~/Resource/Images/thumb_"),
                                                                    fileName));

                            section.Url = string.Format("{0}_{1}_{2}",
                                                        section.Id,
                                                        ConvertToUnSign(section.Name),
                                                        file.FileName);
                            ProcessScaleImage.CreateThumbnail(file.InputStream,
                                                              90,
                                                              60)
                                             .Save(string.Format("{0}{1}",
                                                                 Server.MapPath("~/Resource/Images/thumb_"),
                                                                 section.Url));
                            ProcessScaleImage.CreateThumbnail(file.InputStream,
                                                              section.Width ?? 0,
                                                              section.Height ?? 0)
                                             .Save(string.Format("{0}{1}",
                                                                 Server.MapPath("~/Resource/Images/"),
                                                                 section.Url));
                        }
                        else
                            section.Url = fileName;
                    else
                        section.Url = fileName;

                    UnitOfWork.CSectionRepository.Update(section);
                    UnitOfWork.Save();

                    ViewBag.Completed = true;
                }
            }
            return View(sectionModel);
        }

        public ActionResult AddVideo(int id)
        {
            return View(new CSectionModel
                            {
                                    CategoryId = id,
                                    Activated = true
                            });
        }

        [ValidateInput(false)]
        [HttpPost]
        public ActionResult AddVideo(CSectionModel sectionModel)
        {
            if(string.IsNullOrEmpty(sectionModel.Url))
                ModelState.AddModelError("Url",
                                         "Youtube link is required");
            if(ModelState.IsValid)
            {
                CSection section = sectionModel;
                if(UnitOfWork.CSectionRepository.CheckInsertCSection(section))
                {
                    if(sectionModel.CategoryId.HasValue)
                        section.Category = UnitOfWork.CategoryRepository.SelectbyId(sectionModel.CategoryId.Value);
                    section.Type = CSection.VIDEO;
                    UnitOfWork.CSectionRepository.Insert(section);
                    UnitOfWork.Save();

                    ViewBag.Completed = true;
                }
            }
            return View(sectionModel);
        }

        public ActionResult EditVideo(string id)
        {
            int guid;
            if(int.TryParse(id,
                            out guid))
            {
                CSection section = UnitOfWork.CSectionRepository.SelectbyId(guid);
                if(section != null)
                {
                    CSectionModel sectionModel = section;
                    return View(sectionModel);
                }
            }
            ViewBag.Completed = true;
            return View(new CSectionModel());
        }

        [ValidateInput(false)]
        [HttpPost]
        public ActionResult EditVideo(CSectionModel sectionModel)
        {
            if(string.IsNullOrEmpty(sectionModel.Url))
                ModelState.AddModelError("Url",
                                         "Youtube link is required");
            if(ModelState.IsValid)
            {
                CSection section = UnitOfWork.CSectionRepository.SelectbyId(sectionModel.Id);
                sectionModel.Update(section);
                if(UnitOfWork.CSectionRepository.CheckUpdateCSection(section))
                {
                    UnitOfWork.CSectionRepository.Update(section);
                    UnitOfWork.Save();

                    ViewBag.Completed = true;
                }
            }
            return View(sectionModel);
        }

        [HttpPost]
        public ActionResult DeleteSection(string id)
        {
            if(id != null)
            {
                string[] s = id.Split(',');
                int guid;
                List<int> list = (from s1 in s
                                  where int.TryParse(s1,
                                                     out guid)
                                  select int.Parse(s1)).ToList();

                if(UnitOfWork.CSectionRepository.CheckDeleteCSection(list))
                {
                    UnitOfWork.CSectionRepository.Delete(list);
                    UnitOfWork.Save();
                }
            }
            return Json(new
                            {
                                    status = 1,
                                    msg = "Update Successfully"
                            },
                        JsonRequestBehavior.DenyGet);
        }

        public ActionResult Blank()
        {
            return Content("");
        }

        #endregion
    }
}
